<?php
if (!class_exists('PHPMailer')) 
{
	require_once(CAKE.'Clases/phpmailer/class.phpmailer.php');
}


class EmailHelper extends AppHelper 
{
		var $config = array();
    var $debugInfo = array('debug' => 1, 'emailDebug' => 'sample@company.com'); //0: send emails, 1: send Email only to Debug Email, 2:Off 
    var $variables = array();
		public function __construct(View $view, $settings = array()) 
		{
    	parent::__construct($view, $settings);
			$this->configuracion();
    }

	

/**/


		function configuracion($config = array(), $debugInfo = array('debug' => 1, 'emailDebug' => 'sample@company.com')) {
        $base = array('smtpServidor' => $_SESSION['EMAIL_SERVER_HOST'], 'smtpPuerto' => $_SESSION['EMAIL_SERVER_PORT'], 'smtpSeguridad' => $_SESSION['EMAIL_SECURITY'], 'smtpUsuario' => $_SESSION['EMAIL_SERVER_USER'], 'smtpClave' => $_SESSION['EMAIL_SERVER_PASS'], 'appDomainRoot' => ROOT.DS.WEBROOT_DIR.DS."plantillas", 'skeletonFile' => '', 'emailEngine' => $_SESSION['EMAIL_ENGINE']);
				$configu= array_merge($base,$config);
				foreach ($configu as $key => $value) {
            $this->config[$key] = $value;
        }
        $this->config['skeletonFile'] = (!$this->config['skeletonFile']) ? CAKE.DS."Clases".DS."phpmailer".DS."plantillas".DS."plantilla_email.php" : $this->config['skeletonFile'];
        $this->config['useSmtp'] = true;
        $this->debugInfo['debug'] = $_SESSION['DEBUG'];
        $this->debugInfo['emailDebug'] = $_SESSION['EMAIL_DEBUG'];
    }

    function setVariable($name, $value) {
        $this->variables[$name] = $value;
    }

    function limpiarVariables() {
        $this->variables = array();
    }

    /* funcion para manejar los parametros del servidor y el envio.
     *
     * @param array $para_send				lista de destinatarios
     * @param array $para_send_CC				lista de destinatarios CC
     * @param array $para_send_BCC			lista de destinatarios BCC
     * @param varchar $titulo				Titulo del correo
     * @param text $mensaje					mensaje HTML
     */

    function enviar($de = array('nombre' => 'John', 'email' => 'jdoe@sample.com'), $para = array(), $dataPlantilla, $adjunto = array(), $stringAdjunto = array(), $imagen = array()) {
        $resultEmail = array();

				if(is_array($adjunto)) $adjunto = array_merge(array('ruta' => '', 'nombre' => 'archivo.pdf', 'codificacion' => 'base64', 'tipo' => 'application/octet-stream'), $adjunto);
        if(is_array($stringAdjunto)) $stringAdjunto = array_merge(array('cadena' => '', 'nombre' => 'archivo.pdf', 'codificacion' => 'base64', 'tipo' => 'application/octet-stream'), $stringAdjunto);
        

        $asunto = "";
        $mensaje = array('html' => '', 'texto' => '');

        $skeleton = "";
        if ($this->config['skeletonFile'] != null)
            $skeleton = $this->cargarPlantillaSkeleton($this->config['skeletonFile'], $this->config['appDomainRoot']);

        //$dataPlantilla = $plantilla->find(array('codigo' => $codigoEmailPlantilla));

        if ($dataPlantilla) {
            if ($skeleton != '')
                $contenidoHtml = str_replace('%cuerpo_html%', $dataPlantilla['cuerpo_html'], $skeleton);
            else
                $contenidoHtml = $dataPlantilla['cuerpo_html'];

            $asunto = str_replace('#system_name#', $_SESSION['EMAIL_FROM_NAME'], $dataPlantilla['asunto']);
            $mensaje = array('html' => $contenidoHtml, 'texto' => $dataPlantilla['cuerpo_texto']);
        }

        if ($this->debugInfo['debug'] != 0)
            $asunto = "" . $asunto;


        //$this->variables['#ruta_servidor#'] = DOMAIN_ROOT;
        $this->variables['#system_name#'] = $_SESSION['EMAIL_FROM_NAME'];
        $this->variables['#email_de#'] = $_SESSION['EMAIL_FROM'];
        $this->variables['#email_de_nombre#'] = $_SESSION['EMAIL_FROM_NAME'];
        //$mensaje = str_ireplace("src=\"images", "src=\"" . DOMAIN_ROOT . "images", $mensaje);
        //$mensaje = str_ireplace("background=\"images", "background=\"" . DOMAIN_ROOT . "images", $mensaje);

        foreach ($this->variables as $name => $value) {
            $mensaje = str_replace($name, stripslashes($value), $mensaje);
        }
        switch (strtolower($this->config['emailEngine'])) {
            /*case 'jango':
                $this->enviarJango($de, $para, $asunto, $mensaje, $dataPlantilla, $adjunto);
            break;*/
            case 'local':
                $res=$this->enviarLocal($de, $para, $asunto, $mensaje, $dataPlantilla, $adjunto, $stringAdjunto,$imagen);
            break;
        }
				return $res;
    }

    function enviarLocal($de, $para, $asunto, $mensaje, $dataPlantilla, $adjunto, $stringAdjunto,$imagen) {
        //documentation: http://phpmailer.worxware.com/index.php?pg=methods
        $correo = new PHPMailer();
        $correo->IsSMTP();
        $correo->SetLanguage('es');
        
        if ($this->config['useSmtp']) {
            $correo->SMTPAuth = true;           // Enciente la autenticacion SMTP
            $correo->SMTPSecure = $this->config['smtpSeguridad'];  // SMTP Seguridad
            //$correo->SMTPDebug = 2;
            $correo->Username = $this->config['smtpUsuario'];    // SMTP usuario
            $correo->Password = $this->config['smtpClave'];  // SMTP clave
        }

        $correo->Host = $this->config['smtpServidor'];
        $correo->Port = $this->config['smtpPuerto'];
        $correo->From = $de['email'];
        $correo->FromName = $de['nombre'];
        $correo->CharSet = 'utf-8';

        switch ($this->debugInfo['debug']) {
            case 0: //send email to recipients
                foreach ($para as $indice => $modo){
                    switch($indice){
                        case 'original':
                            foreach ($para[$indice] as $recibe)
                                $correo->AddAddress($recibe);
                        break;
                        case 'copia':
                            foreach ($para[$indice] as $recibe)
                                $correo->AddCC($recibe);
                        break;
                        case 'coculta':
                            foreach ($para[$indice] as $recibe)
                                $correo->AddBCC($recibe);
                        break;
                    }
                }
                break;
            case 1: //send email to debug account
                $emailList = split(",", $this->debugInfo['emailDebug']);
                if (count($emailList) > 0) {
                    foreach ($emailList as $correoD) {
                        $correo->AddAddress($correoD);
                    }
                }
                else
                    $correo->AddAddress($this->debugInfo['emailDebug']);
                break;
        }

        $correo->Subject = $asunto;
				foreach($imagen as $valor){
						if(isset($valor['imagen']) && isset($valor['etiqueta']) && isset($valor['tipo'])){
								$correo->AddEmbeddedImage($valor['imagen'], $valor['etiqueta'], $valor['imagen'],'base64',$valor['tipo']); //'image/jpg'
						}
				}
        
        $correo->Body = $mensaje['html'];
        $correo->AltBody = $mensaje['texto'];
        if (!empty($adjunto['ruta']))
            $correo->AddAttachment($adjunto['ruta'], $adjunto['nombre'], $adjunto['codificacion'], $adjunto['tipo']);
        if (!empty($stringAdjunto['cadena']))
            $correo->AddStringAttachment($stringAdjunto['cadena'], $stringAdjunto['nombre'], $stringAdjunto['codificacion'], $stringAdjunto['tipo']);
        $correo->WordWrap = 80;
        $correo->IsHTML(true);
        $status = $correo->Send();
        $errorInfo = $correo->ErrorInfo;

				$recibe = '';
        
        foreach ($para as $indice => $valor){
            $recibe .= implode(',', $valor);
        }

        $resultEmail['email_envia'] = $de['email'];
        $resultEmail['email_recibe'] = $recibe;
        $resultEmail['email_plantilla_id'] = ($dataPlantilla) ? $dataPlantilla['id'] : 0;
        $resultEmail['estatus'] = ($status != '') ? intVal($status) : 0;
        $resultEmail['estatus_mensaje'] = $errorInfo;

       
        $this->limpiarVariables();

        $correo->ClearAllRecipients();
        $correo->ClearAttachments();
				return  $resultEmail;
    }

    /*function enviarJango($de, $para, $asunto, $mensaje, $dataPlantilla, $adjunto) {
        $client = new SoapClient('http://api.jangomail.com/api.asmx?WSDL');
        switch ($this->debugInfo['debug']) {
            case 0: //enviar email a destinatarios
                foreach ($para as $recipient) {
                    $this->enviarEmailTransaccional($client, $de, $recipient, $asunto, $mensaje, $dataPlantilla, $adjunto);
                }
                break;
            case 1: //enviar correo a la cuenta debug
                $this->enviarEmailTransaccional($client, $de, $this->debugInfo['emailDebug'], $asunto, $mensaje, $dataPlantilla, $adjunto);
                break;
        }
    }

    function enviarEmailTransaccional($client, $de, $recipient, $asunto, $mensaje, $dataPlantilla, $adjunto) {
        $options = "OpenTrack=True,ClickTrack=True,UseSystemMAILFROM=False,TransactionalGroupID=" . $this->config['transGroupID'];
        $arrOptions = array('Username' => $this->config['smtpUsuario'],
            'Password' => $this->config['smtpClave'],
            'FromEmail' => $de['email'],
            'FromName' => $de['nombre'],
            'ToEmailAddress' => $recipient,
            'Subject' => utf8_encode($asunto),
            'MessagePlain' => utf8_encode($mensaje['texto']),
            'MessageHTML' => utf8_encode($mensaje['html']),
            'Options' => $options);
        try {
            $result = $client->SendTransactionalEmail($arrOptions);
            $arrResult = preg_split('/\r\n|\r|\n/', $result->SendTransactionalEmailResult);
        } catch (Exception $e) {
            $arrResult[0] = 1;
            $arrResult[1] = $e->getMessage();
            $arrResult[2] = 0;
        }
        $resultEmail['email_envia'] = $de['email'];
        $resultEmail['email_recibe'] = $recipient;
        $resultEmail['id_email_plantilla'] = ($dataPlantilla) ? $dataPlantilla[0]['id'] : 0;
        $resultEmail['estatus'] = intVal($arrResult[0] == 0 ? 1 : 0);
        $resultEmail['estatus_mensaje'] = addslashes($arrResult[1]);
        $resultEmail['cuerpo_html'] = addslashes($mensaje['html']);
        $resultEmail['cuerpo_texto'] = addslashes($mensaje['texto']);

        $this->save($resultEmail);
        $this->id = null;
        $this->limpiarVariables();
    }*/


		function cargarPlantillaSkeleton($skeletonFile, $domainRoot) {
        $arrFile = file($skeletonFile);
        $contenido = '';
        foreach ($arrFile as $line) {
            $contenido.=$line;
        }
        $contenido = str_replace('%domain_root%', $domainRoot, $contenido);
        return $contenido;
    }

}
